import {
  util
} from "../util"
export class FIleOpera {
  //物理文件路径
  static filePath = `${wx.env.USER_DATA_PATH}/auth.json`;
  //保存文件
  static save(data, callback) {
    //临时文件名称
    let name = 'tmp_auth' + util.getRandomString(); //自定义文件名
    //临时文件路径
    let tempFilePath = `${wx.env.USER_DATA_PATH}/${name}.json`;
    let fsm = wx.getFileSystemManager();
    fsm.writeFile({
      filePath: tempFilePath,
      data: data,
      encoding: "utf8",
      success: () => {
        fsm.saveFile({
          tempFilePath: tempFilePath,
          filePath: FIleOpera.filePath,
          success: () => {
            callback({
              success: true
            });
          },
          fail: (ex) => {
            callback({
              success: false,
              msg: ex.errMsg
            });
          },
        });
      },
      fail: (ex) => {
        callback({
          success: false,
          msg: ex.errMsg
        });
      }
    })

  }
  //读取文件
  static read(callback) {
    let fsm = wx.getFileSystemManager();
    try {
      fsm.accessSync(this.filePath);
      let res = fsm.readFileSync(this.filePath, "utf8");
      console.log(res)
      callback({
        success: true,
        data: JSON.parse(res)
      });
    }
    catch (ex) {
      callback({
        success: false,
        msg: ex.message
      });
    }
  }
  //删除
  static del(callback) {
    let fsm = wx.getFileSystemManager();
    try {
      fsm.unlinkSync(this.filePath)
      if(callback&&typeof(callback)=="function"){
        callback({
          success: true
        });
      }
    } catch (ex) {
      callback({
        success: false,
        msg: ex.message
      });
    }
    // fsm.access({
    //   path:this.filePath,
    //   success:()=>{
    //       fsm.unlink({
    //       filePath:this.filePath,
    //       success:()=>{
    //         if(callback&&typeof(callback)=="function"){
    //         callback({
    //           success: true
    //         });
    //       }
    //       },
    //       fail:(ex)=>{
    //         callback&&callback({
    //           success: false,
    //           msg: ex.errMsg
    //         });
    //       }
    //       })
    //   },
    //   fail:(ex)=>{
    //     callback&&callback({
    //       success: false,
    //       msg: ex.errMsg
    //     });
    //   }
    // });

  }
}